package cn.apestar.common.sms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.*;
import java.util.*;
import java.util.Map.Entry;

public class HttpUtility {

public static HttpPostModel submitByPost(String urlAddress, Map<String, String> map) {
		
		HttpPostModel model=new HttpPostModel();
		StringBuffer params = new StringBuffer();

		Iterator<Entry<String, String>> it = map.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> element = (Entry<String, String>) it.next();
			params.append(element.getKey());
			params.append("=");
			params.append(element.getValue());
			params.append("&");
		}

		if (params.length() > 0) {
			params.deleteCharAt(params.length() - 1);
		}
		
		HttpURLConnection conn = null;
		try {
			URL url = new URL(urlAddress);
			conn = (HttpURLConnection) url.openConnection();

			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", String.valueOf(params.length()));
			conn.setDoInput(true);
			conn.connect();

			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.write(params.toString());
			out.flush();
			out.close();
			model.set_ResponseCode(conn.getResponseCode()); 
			
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			
			model.set_ResponseString(br.readLine());
			
			br.close();			
			
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			conn.disconnect();
		}
		return model;
	}
}
